package com.sws.worktive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.sws.worktive.model.Category;
import com.sws.worktive.task.ServerDownload;
import com.sws.worktive.task.ServerResponse;
import com.sws.worktive.util.ConnectionDector;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.WT_Prefrences;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class DescriptionScreen extends Fragment implements OnClickListener,
		ServerResponse {

	LinearLayout ll_back;
	EditText edtDescription, edtPhoneNumber, edtZipCode;
	Spinner spn_MilesRadius, spn_JobTitle, spn_JobType, spn_Language;

	int val_JobType, val_Language;
	List<NameValuePair> nameValuePairs;

	// ProgressDialog mProgressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		ConnectionDector connectionDector = new ConnectionDector(
				DescriptionScreen.this.getActivity());
		if (connectionDector.isConnectingToInternet()) {
			if (((DrawerScreen) getActivity()).arrCategories.size() == 0) {
				((DrawerScreen) getActivity()).mProgressDialog = ProgressDialog
						.show(getActivity(), "", getActivity().getResources()
								.getString(R.string.posting_jobs));
				ServerDownload serverDownload = new ServerDownload(
						getActivity(), DescriptionScreen.this,
						Constant.TAG_CATEGORY_REQUEST);
				serverDownload.execute(nameValuePairs);
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.description_screen, container,
				false);
		TextView txtHeader = (TextView) view.findViewById(R.id.screen_title);
		txtHeader.setText(getResources().getString(R.string.description));

		ll_back = (LinearLayout) view.findViewById(R.id.layout_back);
		ll_back.setOnClickListener(this);

		edtDescription = (EditText) view.findViewById(R.id.edt_description);
		edtZipCode = (EditText) view.findViewById(R.id.edt_zipcode);
		edtPhoneNumber = (EditText) view.findViewById(R.id.edt_phoneno);

		view.findViewById(R.id.btn_post).setOnClickListener(this);
		spn_JobTitle = (Spinner) view.findViewById(R.id.spn_job_title);
		// ArrayAdapter<Category> adapterJobTitle = new ArrayAdapter<Category>(
		// getActivity(), R.layout.spinner_item,
		// ((DrawerScreen) getActivity()).arrCategories);

		((DrawerScreen) getActivity()).adapterJobTitle
				.setDropDownViewResource(R.layout.spinner_item);
		spn_JobTitle.setAdapter(((DrawerScreen) getActivity()).adapterJobTitle);

		spn_JobTitle.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		spn_JobType = (Spinner) view.findViewById(R.id.spn_job_type);
		ArrayAdapter<CharSequence> adapterJobType = ArrayAdapter
				.createFromResource(DescriptionScreen.this.getActivity(),
						R.array.array_job_type, R.layout.spinner_item);

		adapterJobType.setDropDownViewResource(R.layout.spinner_item);
		spn_JobType.setAdapter(adapterJobType);

		spn_JobType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 0) {

				} else {
					val_JobType = arg2;
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		spn_Language = (Spinner) view.findViewById(R.id.spn_language);
		ArrayAdapter<CharSequence> adapterLanguage = ArrayAdapter
				.createFromResource(DescriptionScreen.this.getActivity(),
						R.array.array_languages, R.layout.spinner_item);

		adapterLanguage.setDropDownViewResource(R.layout.spinner_item);
		spn_Language.setAdapter(adapterLanguage);

		spn_Language.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 0) {

				} else {
					val_Language = arg2;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		return view;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.layout_back:
			FragmentManager fragmentManager = getActivity()
					.getSupportFragmentManager();
			fragmentManager.popBackStack();
			break;

		case R.id.btn_post:

			if (edtDescription.getText().toString().length() < 10) {
				Toast.makeText(getActivity(),
						"Description not be less than 10 character..",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (edtZipCode.getText().toString().length() < 6) {
				Toast.makeText(getActivity(), "Enter valid zipcode..",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				ConnectionDector connectionDector = new ConnectionDector(
						DescriptionScreen.this.getActivity());
				if (connectionDector.isConnectingToInternet()) {
					((DrawerScreen) getActivity()).mProgressDialog = ProgressDialog
							.show(getActivity(),
									"",
									getActivity().getResources().getString(
											R.string.posting_jobs));

					ServerDownload serverDownload = new ServerDownload(
							DescriptionScreen.this.getActivity(),
							DescriptionScreen.this, Constant.TAG_POST_REQUEST);
					serverDownload.execute(postingRequest());
				} else {
					Toast.makeText(
							DescriptionScreen.this.getActivity(),
							getResources().getString(
									R.string.no_internet_connection),
							Toast.LENGTH_SHORT).show();
				}

			}
			break;

		default:
			break;
		}

	}

	List<NameValuePair> postingRequest() {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(Constant.API_PASSWORD,
				Constant.PASSWORD_VALUE));
		nameValuePairs.add(new BasicNameValuePair(Constant.DESCRIPTION,
				edtDescription.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair(Constant.PHONE_NUMBER,
				edtPhoneNumber.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair(Constant.POST_JOB_TYPE,
				val_JobType + ""));
		nameValuePairs.add(new BasicNameValuePair(Constant.ZIPCODE, edtZipCode
				.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair(Constant.LANGUAGE,
				val_Language + ""));

		return nameValuePairs;

	}

	@Override
	public void httpResponse(JSONObject jsonObject, String requestTag) {
		// TODO Auto-generated method stub

		if (requestTag.equals(Constant.TAG_POST_REQUEST)) {
			if (((DrawerScreen) getActivity()).mProgressDialog.isShowing()) {
				((DrawerScreen) getActivity()).mProgressDialog.dismiss();
			}
			if (jsonObject != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonObject.toString());
					if (jsonObj.optInt(Constant.STATUS) == 1) {

						WT_Prefrences prefrences = new WT_Prefrences(
								DescriptionScreen.this.getActivity());
						prefrences.setLastPostTime(System.currentTimeMillis());
						prefrences.setPostAvail(prefrences.getPostAvail() - 1);
						Log.v("CURRENT POST TIME", System.currentTimeMillis()
								+ "");

						Toast.makeText(DescriptionScreen.this.getActivity(),
								jsonObj.optString(Constant.MESSAGE),
								Toast.LENGTH_SHORT).show();
						((DrawerScreen) DescriptionScreen.this.getActivity()).arrJobs
								.clear();

						FragmentManager fragmentManager = getActivity()
								.getSupportFragmentManager();
						fragmentManager.popBackStack();
					} else {

						Toast.makeText(DescriptionScreen.this.getActivity(),
								jsonObj.optString(Constant.MESSAGE),
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		} else if (requestTag.equals(Constant.TAG_CATEGORY_REQUEST)) {
			if (jsonObject != null) {
				((DrawerScreen) getActivity())
						.startJsonParser4RCategory(jsonObject);
			}

		}
	}

}
